<template>
	<view class="content bg-light" style="height: 100%;min-height: 1400rpx;">
		<!-- 顶部标题组件 -->
		<tabsTop :tabName="text"></tabsTop>
		<!-- 搜索框 -->
		<!-- <view class="search">
			<mySearch class="searchClick" @click="searchClick()"></mySearch>
		</view> -->
		<!-- tab栏 -->
		<view class="tab-bar flex mt-2 bg-white "
			style="justify-content: space-around;height: 80rpx;line-height: 40px;position: relative;">
			<view v-for="(item, index) in tabs" :key="index" class="tab-item flex-1 text-center"
				style="font-size: 28rpx;color: #333;cursor: pointer;height: 80rpx;"
				:class="{ active: activeTab === index }" @click="changeTab(index)">
				<text class="font">{{ item }}</text>
			</view>
			<view class="tab-indicator" :style="{ left: leftPosition, width: tabWidth }"></view>
		</view>
		<!-- 订单 -->
		<view class="order-list" style="min-height: 900rpx;">
			<view class="order-item" v-if="orders.length > 0">
				<view v-for="(item,index) in orders" :key="index" class="p-2 m-2 bg-white rounded-lg">
					<!-- 商店名和交易状态 -->
					<view class="flex justify-between align-center">
						<view class="flex align-center" style="line-height: 2.8;">
							<view style="font-size: 28rpx;">小康龙江</view>
							<uni-icons type="right" size="15" class="flex align-center"></uni-icons>
						</view>
						<view style="font-size: 28rpx;">
							{{getRowStatus(item.Row_Status)}}
						</view>
					</view>
					<!-- 商品图、商品信息、价格、数量 -->
					<view v-for="(product, pIndex) in item.children" :key="pIndex" class="flex justify-between mt-1"
						@click="goOrderD(index)">
						<!-- if(product.Row_Status==6) pIndex -->
						<image :src="Domain_IMG+product.Picture_URL" style="width: 104rpx;height: 102rpx;"
							class="rounded-lg img_box">
						</image>
						<view class="flex justify-between" style="width: 82%;">
							<view>
								<view style="font-size: 26rpx;" class="good_name">{{product.Article_Name}}</view>
								<view class="mt-1 good_remark" style="color: #f49c0c;font-size: 20rpx;">{{isSevendays}}
								</view>
							</view>
							<view>
								<view style="font-size: 26rpx;" class="good_name">￥{{product.Sales_Unit_Price}}</view>
								<view class="mt-1 good_remark" style="font-size: 20rpx;text-align-last: end;">
									&times;{{product.Quantity}}
								</view>
								<view v-if="product.Refund_Type == '1'" class="text-danger" style="font-size: 10px;">
									退款审核</view>
								<view v-else-if="product.Row_Status == '4'" class="text-success good_remark1"
									style="font-size: 10px;">退款成功</view>
							</view>
							<!-- <view class="flex">
								<button v-if="item.children.length > 1" v-for="(product, pIndex) in item.children"
									:key="pIndex" @click="goSubOrder(index, pIndex)">商品{{pIndex + 1}}再来一单</button>
							</view> -->
							<!-- 优惠、应付 -->

							<!-- 删除订单、再来一单或订单状态 -->
						</view>
					</view>
					<view>
						<view v-if="item.Row_Status == '0'" class="flex justify-end good_name"
							style="font-size: 24rpx;">
							<!-- <view class="">优惠 ￥{{item.preferential}}&comma;</view> -->
							<view>应付款 ￥{{(getChStatus(item)).toFixed(2)}}</view>
						</view>
						<view v-else class="flex justify-end good_name" style="font-size: 24rpx;">
							<!-- <view class="">优惠 ￥{{item.preferential}}&comma;</view> -->
							<view>实付款 ￥{{(getChStatus(item)).toFixed(2)}}</view>
						</view>
					</view>
					<view class="flex justify-end">
						<view v-if="item.Row_Status == '0'" class="flex justify-end">
							<button @click="cancelOrder(index)" :disabled="loading">取消订单</button>
							<button @click="goOrderD(index)">立即付款</button>
						</view>
						<view v-else class="flex justify-end">
							<button v-if="item.Row_Status != '1'"
								@click="showDeleteConfirm(index)">删除订单</button>
							<!-- <view class="flex justify-end good_name" v-if="item.children.length === 1"
							style="font-size: 24rpx;">
							<button @click="goSubOrder(index)">再来一单</button>
						</view> -->
						</view>
					</view>
					<view v-if="showDeleteConfirmDialog" class="dialog">
						<view class="bg-white" style="width:80%;height:300rpx;">
							<view class="dialog-header text-center m-2">确定删除订单？</view>
							<view class="dialog-content">
								<view class="p-2 text-center">删除订单后无法恢复，无法处理您的售后问题，请慎重考虑。</view>
							</view>
							<view class="dialog-footer">
								<button class="btn-cancel" @click="hideDeleteConfirm">取消</button>
								<button class="btn-delete" @click="deleteOrderConfirm">删除</button>
							</view>
						</view>
					</view>
				</view>
			</view>
			<view v-else class="noOrders">暂无订单</view>
		</view>
		<!-- 底部赞助信息 -->
		<botSponsor></botSponsor>
	</view>
</template>

<script>
	const app = getApp();
	import {
		getOpenIDAction,
		LocationResolution,
		getMemberInfoAction,
		getAddAction,
		RedisAdd
	} from '@/api/global.js';
	import {
		getOrders,
		getWeChatSalesOrder,
		getOneOrder,
		getCancelOrder
	} from '@/api/orders.js';
	import {
		getDeleteAction
	} from '@/api/global.js'
	import tabsTop from "@/components/tabs/tabs-top.vue";
	import tabsBottom from "@/components/tabs/tabs-bottom.vue";
	import mySearch from "@/components/mysearch/mysearch.vue";
	import botSponsor from "@/components/botsponsor/sponsor.vue"
	export default {
		components: {
			tabsTop, //顶部标题组件
			tabsBottom, //底部tab组件
			mySearch, // 搜索组件
			botSponsor // 底部赞助商
		},
		data() {
			return {
				tabs: ["全部", "待付款", "待发货", "待收货", "待评价"], // tab选项
				activeTab: 0, // 当前选中的tab索引，默认为全部订单
				text: '',
				orders: [],
				product_info: '永富蔓小仙蔓越莓银耳鲜炖180g*6瓶',
				form: {
					page: 1,
					limit: 10,
					Open_ID: app.globalData.Open_ID,
					App_ID: app.globalData.App_ID,
					Enterprise_Info_SerialNumber: app.globalData.Enterprise_Info_SerialNumber,
					Row_Status: '',
					Article_Name: '',
				},
				isSevendays: '七天无理由退货',
				Domain_IMG: app.globalData.Domain_IMG,
				showDeleteConfirmDialog: false, // 是否显示删除订单确认弹出框
				deleteIndex: -1, // 待删除订单的索引
				selectShopCar: [],
				loading:false,
			}
		},
		computed: {
			leftPosition() {
				return `calc(${this.activeTab * (100 / this.tabs.length)}% + 5%)`; // 设置 left 样式，初始值为 5%
			},
			tabWidth() {
				return `calc(50% / ${this.tabs.length})`; // 设置选项卡宽度
			}
		},
		onLoad(options) {
			const text = decodeURIComponent(options.text)
			this.text = text
			if (options.hasOwnProperty(options.id)) {
				this.activeTab = options.id
			}
			if (app.globalData.openid == '') {
				uni.showModal({
					title: '检测未登录',
					content: '登陆',
					showCancel: false,
					success(res) {
						if (res.confirm) {
							this.onLogin((loginRes) => {
								console.log(1);
								this.getOpenID(loginRes.code, ls_App_ID, (Res) => {
									uni.setStorageSync('hmgx_open_id', Res.Open_ID)
									this.$scope.globalData.Open_ID = Res.Open_ID
									app.memberInfo.Open_ID = Res.Open_ID
									if (app.globalData.memberInfo) {
										uni.redirectTo({
											url: '/pages/my/order?id=0'
										})
									}
								})
							})
							uni.login({
								provider: "weixin",
								success: function(loginRes) {
									uni.request({
										header: {
											'Content-Type': 'application/x-www-form-urlencoded'
										},
										url: app.globalData.Domain_Name + "/WXSecret2",
										method: "POST",
										data: {
											Data: loginRes.code
										},
										success: (re) => {
											console.log('re', re)
											app.globalData.openid = re.data.openid
											app.globalData.memberInfo = re.data.openid
											if (app.globalData.memberInfo) {
												uni.redirectTo({
													url: '/pages/my/order?id=0'
												})
											}
										}
									})
								},
							})
						}
					}
				})
			}

			// 根据传递的参数判断应该跳转到哪个选项卡
			switch (text) {
				case '待付款':
					this.activeTab = 1;
					this.form.Row_Status = 0;
					break;
				case '待发货':
					this.activeTab = 2;
					this.form.Row_Status = 1;
					break;
				case '待收货':
					this.activeTab = 3;
					this.form.Row_Status = 6;
					//1
					break;
				case '待评价':
					this.activeTab = 4;
					this.form.Row_Status = 10;
					break;
				default:
					this.activeTab = 0; // 默认为全部订单
					this.form.Row_Status = '';
					break;
			}
			this.getData(this.form)
		},
		// onShow() {
		// 	this.getData(this.form)
		// },
		methods: {
			onLogin(callback) { //获取用户登录Code码
				uni.login({
					provider: "weixin",
					success: function(loginRes) {
						callback(loginRes)
					}
				})
			},
			async getOpenID(Code, App_ID, callback) { //获取用户Open_ID
				callback(await getOpenIDAction({
					Code,
					App_ID
				}))
			},
			async changeTab(index) {
				this.activeTab = index;
				switch (index) {
					case 1:
						this.form.Row_Status = 0;
						break;
					case 2:
						this.form.Row_Status = 1;
						break;
					case 3:
						this.form.Row_Status = 6;
						break;
					case 4:
						this.form.Row_Status = 10;
						break;
					default:
						this.form.Row_Status = '';
						break;
				}
				this.getData(this.form);
			},
			searchClick() {
				// 搜索框点击事件
			},
			async cancelOrder(index) {
				this.loading = true;
				console.log('333', this.orders);
				
				const res = await getCancelOrder({
					Enterprise_Info_SerialNumber: app.globalData.Enterprise_Info_SerialNumber,
					Open_ID: app.globalData.Open_ID,
					Collection_SerialNumber: this.orders[index].Collection_SerialNumber
				})
				if (res.Status == "success") {
					uni.showToast({
						title: '取消成功！',
						icon: 'success'
					})
					this.getData(this.form);
					this.loading = false;
				} else {
					uni.showToast({
						title: '取消失败！',
						icon: 'error'
					})
					this.loading = false;
				}
				
			},
			// payOrder(index) {
			// 	uni.navigateTo({
			// 		url: `/pages/my/orderDetails?order=${encodeURIComponent(JSON.stringify(this.orders[orderIndex]))}`
			// 	});
			// },
			goOrderD(orderIndex) {
				// uni.navigateTo({
				// 	url: `/pages/my/orderDetails?order=${encodeURIComponent(JSON.stringify(this.orders[orderIndex]))}`
				// });
				uni.navigateTo({
					url: `/pages/my/orderDetails?Collection_SerialNumber=${this.orders[orderIndex].Collection_SerialNumber}`
				});
			},
			async getData(form) {
				console.log('form', form);
				const res = await getWeChatSalesOrder(form)
				console.log('111', res);
				console.log('222', app.globalData.Enterprise_Info_SerialNumber);
				this.orders=[];
				res.tableData.forEach(item=>{
					if(item.Order_Type=='10'&&item.Row_Status=='0'){
						
					}else{
						this.orders.push(item);
					}
				})
			
				if (this.activeTab == 2) {
					this.form.Row_Status = 6;
					const res1 = await getWeChatSalesOrder(form);
					const ordersNew = res1.tableData;
					if (res1.limit != 0) {
						ordersNew.forEach(item => {
							this.orders.push(item);
						})
					}
					console.log('this.activeTab==2orders', this.orders);
				} else if (this.activeTab == 3) {
					this.form.Row_Status = 1;
					const res1 = await getWeChatSalesOrder(form);
					const ordersNew = res1.tableData;
					if (res1.limit != 0) {
						// this.$set()
						ordersNew.forEach(item => {
							this.orders.push(item);
						})
					}
					console.log('this.activeTab==3orders', this.orders);
				}
				console.log('orders111', this.orders);
				const row1 = []
				console.log('this.activeTab', this.activeTab);
				this.orders.forEach(item => {

					const row = []
					item.children.forEach(item1 => {
						if (item1.Row_Status == 6 && this.activeTab == 2) {

						} else if ((item1.Row_Status == 1 || item1.Row_Status == 9) && this
							.activeTab == 3) {

						} else {
							row.push(item1);
						}
					})
					item.children = row;
					if (row.length != 0) {
						row1.push(item);
					}
				})
				this.orders = row1;
			},
			getRowStatus(status) {
				switch (status) {
					case '0':
						return "等待买家付款";
					case '1':
						return "买家已付款";
					case '3':
						return "交易关闭";
					case '4':
						return "已退款";
					case '6':
						return "发货中";
					case '7':
						return "已送达";
					case '8':
						return "购物车";
					case '9':
						return "待发货";
					default:
						return "";
				}
			},
			getChStatus(row) {
				let priceMap = {};
				row.children.forEach(item => {
					let status = item.Row_Status;
					let price = parseFloat(item.Sales_Unit_Price);
					let quantity = parseInt(item.Quantity);

					if (!priceMap[status]) {
						priceMap[status] = 0;
					}

					priceMap[status] += price * quantity;
				});

				// console.log('priceMap', priceMap);
				let totalPrice = Object.values(priceMap).reduce((acc, curr) => acc + curr, 0);
				// console.log('totalPrice', totalPrice);
				return totalPrice;
			},
			getRefundSta(status) {
				switch (status) {
					case '0':
						return "退款中";
					default:
						return "";
				}
			},
			// 显示删除订单确认弹出框
			showDeleteConfirm(index) {
				this.showDeleteConfirmDialog = true;
				this.deleteIndex = index;
			},
			// 隐藏删除订单确认弹出框
			hideDeleteConfirm() {
				this.showDeleteConfirmDialog = false;
			},
			// 确认删除订单
			async deleteOrderConfirm() {
				const res = await getDeleteAction({
					Open_ID: app.globalData.Open_ID,
					TableName: 'collection',
					Primary_Key_Name: 'Collection_SerialNumber',
					Primary_Key: this.orders[this.deleteIndex].Collection_SerialNumber,
					Row_Status: '10',
				})
				if (res.Status == "success") {
					this.hideDeleteConfirm();
					console.log('this.orders', this.orders);
					await this.getData(this.form);
				}
				console.log(res);
			},
			async goSubOrder(index) {
				console.log('order', this.orders);
				console.log('this.orders[index].children[0].Sales_Unit_Price_Stock_SerialNumber', this
					.orders[index]
					.children[0].Sales_Unit_Price_Stock_SerialNumber);
				const res = await getOneOrder({
					Sales_Unit_Price_Stock_SerialNumber: this.orders[index].children[0]
						.Sales_Unit_Price_Stock_SerialNumber
				})
				if (res.Status == "success") {
					console.log('res.Data[0]', res.Data);
					var good = JSON.stringify(res.Data)
					uni.navigateTo({
						url: '/pages/index/submitOrder?good=' + good
					})
				}
				// console.log(res);
			}
		}
	}
</script>

<style>
	.tab-item.active {
		color: #00bfff;
	}

	.tab-indicator {
		position: absolute;
		top: 70rpx;
		left: 0;
		height: 8rpx;
		background-color: #00bfff;
		transition: left 0.3s;
	}

	@media screen and (max-width:800px) {
		button {
			margin: 10rpx;
			padding: 0px;
			font-size: 20rpx;
			height: 56rpx;
			width: 126rpx;
			/* padding: 10rpx 20rpx; */
			border-radius: 24rpx;
			text-align: center;
			margin-top: 24rpx;
			background-color: transparent;
		}
	}

	@media screen and (min-width:800px) {
		.tab-indicator {
			top: 90rpx;
		}

		.img_box {
			width: 300rpx !important;
			height: 280rpx !important;
		}

		.good_name {
			font-size: 40rpx !important;
		}

		.good_remark {
			font-size: 30rpx !important;
		}

		.good_remark1 {
			font-size: 25rpx !important;
		}

		button {
			margin: 10rpx;
			padding: 0px;
			font-size: 30rpx;
			padding: 10rpx 20rpx;
			border-radius: 24rpx;
			text-align: center;
			margin-top: 24rpx;
			background-color: transparent;
		}

		uni-button:after {
			height: 75% !important;
		}

	}

	.noOrders {
		position: absolute;
		top: 50%;
		left: 50%;
		transform: translate(-50%, -50%);
		color: #d6d9db;
	}

	.dialog {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		background-color: rgba(0, 0, 0, 0.5);
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		border-radius: 20rpx;
	}

	.dialog-header {
		font-size: 28rpx;
	}

	.dialog-content {
		font-size: 24rpx;
	}

	.dialog-footer {
		display: flex;
		justify-content: center;
	}

	.btn-cancel,
	.btn-delete {
		border-radius: 8rpx;
		cursor: pointer;
	}

	.btn-cancel {
		background-color: #eaeaea;
	}

	.btn-delete {
		background-color: #ff4e4e;
		color: #fff;
	}
</style>